<template>
  <view>
	  <!-- 公共组件-每个页面必须引入 -->
	  <public-module></public-module>
	   <div class="login-page">
		   <div class="logo-text">
			   <div style="font-size:34px">Hello!</div>
			   自己人的塑料产业平台！
		   </div> 
		   <div class="logo-title">
			   <div class="title-item" :class="{'choose':type=='code'}" @click="changeType('code')">验证码登录</div>
			   <div class="title-item" :class="{'choose':type=='passWord'}" @click="changeType('passWord')">密码登录</div>
		   </div>
		   <u--form labelPosition="left" :model="form" :rules="rules" ref="form" labelWidth="0" errorType="toast">
		   	<div v-if="type == 'code'">
		   		<u-form-item label=" " prop="mobile">
		   			<u-input placeholder="请输入手机号" fontSize="26rpx" shape="circle" border="none" :customStyle="style" v-model="form.mobile"></u-input>
		   		</u-form-item>
		   		<u-form-item  label="" prop="code">
		   			<u-input placeholder="请输入验证码" v-model="form.code" fontSize="26rpx" shape="circle" border="none" :customStyle="style" type="text">
						<template slot="suffix">
							<u-button @click="handleSendLoginSMSCode" :disabled="sendCode" :text="verifyCodeText" size="mini" type="success"></u-button>
						</template>
					</u-input>
		   		</u-form-item>	
		   	</div>
			<div v-else>
				<u-form-item label=" " prop="mobile">
					<u-input placeholder="请输入手机号" fontSize="26rpx" shape="circle" border="none" :customStyle="style" v-model="form.mobile"></u-input>
				</u-form-item>
				<u-form-item  label="" prop="password">
					<u--input placeholder="请输入登录密码" v-model="form.password" fontSize="26rpx" shape="circle" border="none" :customStyle="style" type="password">
					</u--input>
				</u-form-item>	
			</div>
		   </u--form>
		   
		   <div style="margin-top:50rpx;">
				<u-button text="登 录" color="linear-gradient(180deg, #FFA470 0%, #FF5E01 100%)" shape="circle" @click="handleLogin" :loading="btnLoading"></u-button>
		   </div>
		   <div class="login-two">
			   <div>没有账号？<span style="color:#FF5E01;cursor: pointer;" @click="topage('/pagesCommon/register')">免费注册</span></div>
			   <div @click="topage('/pagesCommon/forgetPassword')">忘记密码？</div>
		   </div>
		   
		   <div style="margin-top:80rpx;text-align: center;">
			   <u-divider text="微信快速登录"></u-divider>
			   <img src="https://pic.moresu.com/FgXnlzoPaPG_dn_8j6avAeraJDom" style="width:72rpx" @click="wxLogin">
		   </div>
		   

	   </div>
	  
	   
  </view>

</template>

<script>
	const defaultForm = {
	  password: '',
	  mobile:'',
	  code:'',
	};
  import { mapState, mapMutations } from 'vuex';
  import {login,sendSms,getWXLoginInfo} from '@/config/api.js'
  import store from '@/store';
  import md5 from "@/config/md5.js";
  export default {
    components: {
      
    },
	
	data() {
		return {
	       type:'code',
		   form:JSON.parse(JSON.stringify(defaultForm)),
		   style:{
			   background:'#F6F6F6',
			   padding:'0 40rpx',
			   height:'80rpx'
		   },
		   rules:{
			   code: [{
						required: true,
						message: '请输入验证码',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['blur', 'change']
					}],
			   mobile: [{
					required: true,
					message: '请输入手机号',
					// 可以单个或者同时写两个触发验证方式
					trigger: ['blur', 'change']
				},
				{
					// 自定义验证函数，见上说明
					validator: (rule, value, callback) => {
						// 上面有说，返回true表示校验通过，返回false表示不通过
						// uni.$u.test.mobile()就是返回true或者false的
						return uni.$u.test.mobile(value);
					},
					message: '手机号码不正确',
					// 触发器可以同时用blur和change
					trigger: ['change','blur'],
				}],
				password: [{
					required: true,
					message: '请输入密码',
					// 可以单个或者同时写两个触发验证方式
					trigger: ['blur', 'change'],
					},
					{
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// uni.$u.test.mobile()就是返回true或者false的
							if(value.length < 3){
								return false
							}else{
								return true
							}
						},
						message: '密码长度不小于3',
						// 触发器可以同时用blur和change
						trigger: ['change','blur'],
					}],
				
			},
		   btnLoading:false,
		   sendCode:false,//是否能发送验证码
		   falg: false, //是否倒计时
		   reciprocalTime : null,//倒计时函数
		   verifyCodeText:'获取短信验证码',
		   timer: 60,//倒计时秒数
		   show:false,
		   redirectPath:''
		};
	},
	async onLoad(options) {
		// #ifdef H5
		this.redirectPath = options.redirectPath
		const url = window.location.href
		const code = url.match(/=(\S*)&state=STATE#/)
		// console.log(code)
		// console.log(code[1] )
		if (code !== null) {
		   // 如果能获得code，说明需要处理url并跳转，如果不能获得code，不用处理
		   let replaceUrl = 'http://' + window.location.host + '/#/pagesCommon/login/?code=' + code[1] + '&state=STATE'
		   if(options.redirectPath){
			   replaceUrl = 'http://' + window.location.host + '/#/pagesCommon/login/?code=' + code[1] + '&state=STATE&redirectPath='+options.redirectPath
		   }
		  // alert(replaceUrl)
		  return location.replace(replaceUrl)
		}else{
			let wxcode = options.code
			// alert("++++++++++++++"+wxcode)
			if(wxcode && wxcode != ''){
				getWXLoginInfo({code:wxcode}).then((data)=>{
					// alert(data.isBind)
					// alert(data.unionid)
					if(!data.isBind){ //需要绑定账户
						uni.showToast({
							title:'正在跳转...',
							icon:'none'
						})	
						uni.navigateTo({
							url: '/pagesCommon/bindAccount?unionid='+data.unionid
						})
						// this.$router.push({path:'/pagesCommon/bindAccount?unionid='+data.unionid})
					}else{ //不需绑定，直接跳转
						uni.showToast({
							title:'正在跳转...',
							icon:'none'
						})
						store.dispatch('userInfo',data.unionid).then(()=>{
							this.countRedirect();
						})
						if(uni.getStorageSync('qdClosed')){
							uni.removeStorageSync('qdClosed');
						}
					}
				})
			}
		}
		// #endif
		
		// #ifdef MP
		this.$refs.uForm.setRules(this.rules)
		// #endif
	},
    methods: {
      ...mapMutations(['setUserInfo']),
	  
		  topage(url){
			  uni.navigateTo({
					url: url
			  })
			  // this.$router.push({path:url})
		  },
	      /**
	       * 倒计时
	       * @return null
	       */
	      showCountDown () {
	        this.verifyCodeText = this.timer + '秒后重新获取';
	        this.falg = true;
	        let self = this;
	        self.reciprocalTime = function(time){
	          //@ts-ignore : js setTimeout
	          setTimeout(() =>{
	            if(time >=1 && self.falg){
	              time--;
	              self.verifyCodeText=time + '秒后重新获取';
	              self.reciprocalTime(time);
	            }else{
	              self.verifyCodeText='获取短信验证码';
	              self.sendCode = false;
	              //@ts-ignore : js clearTimeout
	              clearTimeout(self.reciprocalTime);
	            }
	          },1000);
	        };
	        self.reciprocalTime(this.timer);
	      },
	  
	      /**
	       * 发送验证码
	       */
	      handleSendLoginSMSCode(){
	        if(!uni.$u.test.mobile(this.form.mobile)){
	          uni.showToast({
	          	title:'请输入正确的手机号',
	          	icon:'none'
	          })	
	          return
	        }
	        this.sendCode = true;
			console.log("md5",md5)
	        let encryption =  md5.hex_md5(this.form.mobile + 'moresu.,!');
	        sendSms({mobile:this.form.mobile,encryption,type:'CODE_LOGIN'}).then(()=>{
				uni.showToast({
					title:'验证码已发送',
					icon:'none'
				})
	          this.showCountDown();
	        }).catch(()=>{
	          this.sendCode = false;
	        })
	  
	      },
    
	    changeType(type){
	         this.type = type ;
			 this.form = JSON.parse(JSON.stringify(defaultForm))
			 this.verifyCodeText='获取短信验证码';
			 this.sendCode = false;
			 //@ts-ignore : js clearTimeout
			 clearTimeout(this.reciprocalTime);
			 this.falg = false
	      },
		  
		   //微信登录
		  wxLogin(){
			  let host = window.location.host
			   let redirectPath = ''
			  if(this.redirectPath){
				 redirectPath = '?redirectPath='+this.redirectPath
			  } 
			  let redirect_uri = encodeURIComponent('http://'+host+'/#/pagesCommon/login'+redirectPath);
			  let wx_url =
				  "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf86f5e3a191467c6&response_type=code&scope=snsapi_userinfo"+
				  "&redirect_uri=" +redirect_uri +
				  "&state=STATE#wechat_redirect";
				  uni.showToast({
				  	title:'正在跳转...',
				  	icon:'none'
				  })
			  // console.log("redirect_uri")
			  // console.log(redirect_uri)
			  window.location.replace(wx_url) ;
		  },
           
		handleLogin() {
             this.$refs.form.validate().then(res => {
				 // console.log("---------------")
                this.loading = true;
                let pamas = {};
                pamas.mobile = this.form.mobile;
                if(this.type == 'passWord'){
                  pamas.password = this.form.password;
                }else{
                  pamas.code = this.form.code
                }
                login(pamas).then((data)=>{
					// console.log("+++++++++++")
                  let storeUserInfo = {}
                  storeUserInfo.mobile = data.userInfo && data.userInfo.mobile ? data.userInfo.mobile : '';
                  storeUserInfo.userHeader = data.userInfo && data.userInfo.userHeader ? data.userInfo.userHeader : ''
                  storeUserInfo.userName = data.userInfo && data.userInfo.userName ? data.userInfo.userName : '';
                  storeUserInfo.realName  = data.userInfo && data.userInfo.realName ? data.userInfo.realName : '';
                  storeUserInfo.userId = data.userInfo && data.userInfo.userId ? data.userInfo.userId : '';
                  // storeUserInfo.wxOpenId = data.userInfo && data.userInfo.wxOpenId ? data.userInfo.wxOpenId : '';
                  // storeUserInfo.wxUnionId = data.userInfo && data.userInfo.wxUnionId ? data.userInfo.wxUnionId : '';
                  storeUserInfo.promoterCode = data.userInfo && data.userInfo.promoterCode ? data.userInfo.promoterCode : '';
                  storeUserInfo.isBuyerAuth = data.userInfo && data.userInfo.isBuyerAuth ? data.userInfo.isBuyerAuth : 0;
                  storeUserInfo.isSellerAuth = data.userInfo && data.userInfo.isSellerAuth ? data.userInfo.isSellerAuth : 0;
                  storeUserInfo.storeId = data.userInfo && data.userInfo.storeId ? data.userInfo.storeId : '';
                  storeUserInfo.storeName = data.userInfo && data.userInfo.storeName ? data.userInfo.storeName : '';
                  storeUserInfo.permissions = data.userInfo && data.userInfo.permissions ? data.userInfo.permissions : [];
                  storeUserInfo.newUserMsg   = data.userInfo && data.userInfo.newUserMsg  ? data.userInfo.newUserMsg   : '';
                  storeUserInfo.noAuthMsg = data.userInfo && data.userInfo.noAuthMsg ? data.userInfo.noAuthMsg : '';
                  storeUserInfo.token = data.token
                  // console.log("storeUserInfo",storeUserInfo)
                  this.setUserInfo(storeUserInfo)
                  this.loading = false;
				   // console.log("222222222222222222")
                   this.countRedirect()
				   if(uni.getStorageSync('qdClosed')){
				   	uni.removeStorageSync('qdClosed');
				   }
                }).catch((err)=>{
                  this.loading = false;
                })
            })
          },
		  
		   //登录跳转页转换
		  countRedirect(){
			  // alert(this.$route.query.redirectPath)
			 if(this.redirectPath){
				  let redirectPath = this.redirectPath.replace('-','?')
				  redirectPath = redirectPath.replace('|','&')
				   console.log("redirectPath222",redirectPath)
			       if(redirectPath.indexOf('index') != -1 || redirectPath.indexOf('addInquiry')!= -1 || redirectPath.indexOf('price') != -1 ||  redirectPath.indexOf('inquiryList')!= -1 ){
					   uni.switchTab({
							url: redirectPath
					   })
				   }else{
					  uni.navigateTo({
						 url: redirectPath
					  }) 
				   }
				  
				  // this.$router.push({path:redirectPath})
			 }else{
				uni.switchTab({
					url: "/pages/index/index"
				 })
			      // this.$router.push({path:"/"})
			 }
		  },
      },
	  
   
  }
</script>

<style lang="scss">
	@import '@/style/common.scss';
	.login-page{
		padding: 0 40rpx;
		background: url('https://pic.moresu.com/FnqTgF_D7dstwjAKWgKbd0eOCIG9') no-repeat top left #fff;
		background-size: cover;
		height:100vh;	
		.logo-text{
			color:#FF5E01;
			font-size:34rpx;
			font-weight: bold;
			padding:110rpx 0 60rpx 50rpx;
		}
		.logo-title{
			height:60rpx;
			overflow: hidden;
			.title-item{
				float:left;
				font-size: 25rpx;
				color: #070D14;
				cursor: pointer;
				margin-left:50rpx;
				cursor: pointer;
			}
			.title-item.choose{
				font-weight: bold;
				font-size:27rpx;
				position: relative;
			}
			.title-item.choose:before{
				content: ' ';
				position: absolute;
				bottom:-6rpx;
				left:50%;
				margin-left:-33rpx;
				width: 66rpx;
				height: 16rpx;
				background: rgba(255,164,112,0.8);
				border-radius: 8rpx;	
			}
		}
		.login-two{
			@include flexbox(space-between,center);
			font-size: 23rpx;
			color: #8B8B8B;
			margin-top:40rpx;
		}
	}
	
	
</style>